// pages/pallet_details/pallet_details.js
var app = getApp();
var util = require('../../util.js');
var today = util.formatDate(new Date(), 'YYYY-MM-dd');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pallet_select:false,
    options:0,
    options_value: "",
    time: '00:00',
    date: today,
    palletid: 0,
    truckList: [],
    index: 0,
    vehicleId:0,
    defaultUnitIndex: 0,      // 默认重量单位
    unitData: ['吨', '40寸集装箱', '20寸集装箱'],  // 模拟数据
    defaultUnit: ''
  },


  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  bindTimeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },

  // 选择接单车辆
  chooseTruck: function(e){
    var curindex = e.detail.value;
    this.setData({
      vehicleId: this.data.truckList[curindex].id,
      index: curindex
    })
  },

  optionsSelect:function(e){
    var cur = e.currentTarget.dataset.cur;
    var value = e.currentTarget.dataset.value;
    console.log(value);
    this.setData({
      options: cur,
      options_value: value,
    })
  },
  //输入重量
  input:function(res){
    this.setData({
      options_value: res.detail.value,
    })
  },
  submit:function(){
    var that = this;
    //是否已经提交审核信息
    app.getLoginSession(function (session) {
      wx.request({
        url: app.api + '/wx_log_test/user/apporve?token=' + session,
        success: function (event) {
          var res = event.data;
          console.log(res);
          if (res.msg == "OK") {
            if (res.data.driver.status == 1) {
              // 数据验证
              var time = that.data.date + 'T' + that.data.time + ':00';
              var timeOrigin = that.data.date + ' ' + that.data.time;
              time = Date.parse(new Date(time));
              var startTime = Date.parse(new Date(that.data.sendDate1));
              var endTime = Date.parse(new Date(that.data.sendDate2));
              if (time < startTime || time > endTime) {
                wx.showModal({
                  title: '提示',
                  content: '您选择时间不在范围内',
                })
                return false;
              }
              if (!/^\d+(\.\d+)?$/.test(that.data.options_value)) {
                wx.showModal({
                  title: '提示',
                  content: '请输入正确的接单重量！',
                  showCancel: false
                })
                return false;
              }
              console.log(that.data.options_value);
			  if (that.data.options_value > that.data.cargo.remain || that.data.options_value == 0) {
                wx.showModal({
                  title: '提示',
                  content: '接单重量超过货盘余量，请重新选择',
                  showCancel: false
                })
                return false;
              } 
              
              // 确定接单提示
              wx.showModal({
                title: '提示',
                content: '您预约了 ' + timeOrigin +' 去提货，确定接单吗？',
                success: function(res){
                  if(res.confirm){
                      //这里放接口
                      app.getLoginSession(function (session) {
                        wx.request({
                          url: app.api + '/wx_log_test/order/new?token=' + session,
                          data: {
                            cargoId: that.data.palletid,
                            deliveryOn: time,
                            goodWeight: that.data.options_value,
                            vehicleId: that.data.vehicleId,
                          },
                          method: 'POST',
                          header: {
                            'content-type': 'application/json'
                          },
                          success: function (e) {
                            console.log('submit order', e);
                            if (e.statusCode != 200) {
                              wx.showModal({
                                title: '提示',
                                content: "接口返回错误，状态码：" + e.statusCode,
                              })
                            } else {
                              var data = e.data;
                              if (data.msg != 'OK') {
                                wx.showModal({
                                  title: '提示',
                                  content: data.msg,
                                })
                              } else {
                                wx.reLaunch({
                                  url: '/pages/order/order'
                                })
                              }
                            }
                          }
                        })
                      })
                  }
                }
              })
            }else{
              wx.showModal({
                title: '温馨提示',
                content: '您还没有入驻，入驻成功后才能接单',
                showCancel: false
              })
              return false;
            }
          }else{
            wx.showModal({
              title: '温馨提示',
              content: '您还没有入驻，入驻成功后才能接单',
              showCancel: false
            })
            return false;
          }
        },
        fail: function (res) {
        }
      })
    })
  }, 

  bindSelect:function(e){
    var cur = e.currentTarget.dataset.cur;
    console.log(cur);
    this.setData({
      pallet_select: cur,
    })
  },

  call: function (res) {
    wx.makePhoneCall({
      phoneNumber: res.currentTarget.dataset.num
    })
  },

  // 获取司机车辆
  getVehicle : function(res){
    var that = this;
    app.getLoginSession(function (session) {
      wx.request({
        url: app.api + '/wx_log_test/vehicle/list',
        data: {
          token: session
        },
        success: function (res) {
          var res = res.data;
          if (res.msg == "OK") {
            that.setData({
              truckList: res.data,
              vehicleId: res.data[0].id,
            })
          } else {
            that.setData({
              loadtips: res.msg
            })
          }
        }
      })
    })
  },

  // 获取货盘信息
  getPalletInfoById: function (res) {
    var that = this;
    app.getLoginSession(function (session) {
      wx.request({
        url: app.api + '/wx_log_test/cargo/' + that.data.palletid,
        data: {
          token: session
        },
        success: function (res) {
          var res = res.data;
          if (res.msg == "OK") {
            var data = res.data;
            that.setData({
              cargo: data,
              sendDate1: util.formatDate(new Date(data.send_date1), 'YYYY-MM-dd hh:mm:ss'),
              sendDate2: util.formatDate(new Date(data.send_date2), 'YYYY-MM-dd hh:mm:ss'),
			  unit: data.unit,
              loading: false
            })
          } else {
            that.setData({
              loading: false,
              loadtips: res.msg
            })
          }
        },
        fail: function (res) {
          that.setData({
            loading: true
          })
        }
      })
    })
  },


  // 单位选择器改变事件
  unitPickerChange: function(e) {
    this.setData({
      defaultUnit: this.data.unitData[e.detail.value]
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      options: options,
      palletid: options.palletid,
      defaultUnit: this.data.unitData[this.data.defaultUnitIndex] // 页面初始化的时候初始化单位数据
    });

    

    // 获取货盘信息
    this.getPalletInfoById();
    // 获取司机车辆
    this.getVehicle();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})